package com.example.demo.controller;

import lombok.extern.slf4j.Slf4j;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.data.redis.core.RedisTemplate;
import org.springframework.stereotype.Controller;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestMethod;
import org.springframework.web.bind.annotation.RequestParam;
import org.springframework.web.bind.annotation.ResponseBody;

import java.util.HashMap;
import java.util.Map;
import java.util.Random;
import java.util.concurrent.TimeUnit;

@Slf4j
@Controller
@RequestMapping("/code")
public class SendCodeController {

    @Autowired
    private RedisTemplate<String, String> redisTemplate;

    // 发送验证码接口
    @ResponseBody
    @RequestMapping(value = "/sendVerificationCode", method = RequestMethod.POST)
    public Map<String, Object> sendVerificationCode(@RequestParam String phoneNumber, @RequestParam String codeType) {
        Map<String, Object> result = new HashMap<>();

        // 检查是否已经发送过验证码
        String codeKey = getCodeKeyByType(phoneNumber, codeType);
        if (redisTemplate.hasKey(codeKey)) {
            result.put("code", 400);
            result.put("message", "验证码已发送，1分钟后可再次发送，请勿频繁请求");
            return result;
        }

        // 生成随机6位数字验证码
        String verificationCode = generateRandomCode();

        // 存储验证码到 Redis，设置有效期
        int expiration = getExpirationByType(codeType);
        redisTemplate.opsForValue().set(codeKey, verificationCode, expiration, TimeUnit.MINUTES);

        result.put("code", 200);
        result.put("message", "验证码发送成功");
        // 记录验证码到日志
        log.info("验证码已发送至手机号 {}，类型为 {}，验证码为：{}", phoneNumber, codeType, verificationCode);
        return result;
    }

    // 生成随机6位数字验证码
    private String generateRandomCode() {
        Random random = new Random();
        int code = 100000 + random.nextInt(900000); // 生成100000到999999之间的随机数
        return String.valueOf(code);
    }

    // 根据验证码类型获取存储键
    private String getCodeKeyByType(String phoneNumber, String codeType) {
        return "verificationCode:" + codeType + ":" + phoneNumber;
    }

    // 根据验证码类型获取有效期（分钟）
    private int getExpirationByType(String codeType) {
        switch (codeType) {
            case "verificationCode1": // 用户登录
                return 3;
            case "verificationCode2": // 用户注册
                return 3;
            case "verificationCode3": // 修改密码
                return 3;
            case "verificationCode4": // 更改信息
                return 3;
            default:
                return 3; // 默认3分钟
        }
    }


}


